<?php
/**
 * 框架初始化文件
 * 
 * 将一些处理方式固定化，例如，统一魔术引用
 * 
 * @category   Framework
 * @package    __init__
 * @author     Xinze <xinze@live.cn>
 * @copyright  Copyright (c) 2010, 黄新泽
 * @version    1.0
 * @todo       
 */
if (!is_php('5'))
{
    die('Zero Framework runtime environment required PHP version higher than 5.0！');
}

if (!defined('SAPI'))
{
    define('SAPI', php_sapi_name());
}

//设置转义信息
//如果<=5.3,运行。
if (!is_php('5.3'))
{
    ini_set('magic_quotes_runtime', 0); 
}

@ini_set('magic_quotes_sybase', 0);

Zero_Registry::set('magic_quotes_gpc', get_magic_quotes_gpc());
Zero_Registry::set('magic_quotes_runtime', get_magic_quotes_runtime());

if(!defined('LIB_PATH'))
{
    die('请先定义框架地址：LIB_PATH');
}

//set_include_path(get_include_path() . PATH_SEPARATOR . LIB_PATH);
set_include_path(LIB_PATH . PATH_SEPARATOR . MOD_PATH);

//friend url
$PatternManager = new Zero_Url_PatternManager();
$PatternManager->addPattern('default', $pattern, $rules, $defaults);

if (isset($_SERVER['PATH_INFO']))
{
    $PatternManager->setSubjectUrl($_SERVER['PATH_INFO']);

    $path_info_get = $PatternManager->getAttributes();
}
else
{
    $path_info_get = array();
}

$_GET          = array_merge($_GET, $path_info_get);
$_REQUEST      = array_merge($_REQUEST, $path_info_get);

if (Zero_Registry::get('magic_quotes_gpc'))
{
    $_POST    = unquotes($_POST);
    $_GET     = unquotes($_GET);
    $_REQUEST = unquotes($_REQUEST);
    $_COOKIE  = unquotes($_COOKIE);
    $_FILES   = unquotes($_FILES);
}

//初始化目录
if (!file_exists(APP_PATH . '/configs/config.ini.php'))
{
    if (!copy_dir(LIB_PATH . '/Zero/app', APP_PATH))
    {
    }

    //include '__init_locale__.php';
}

function copy_dir($source, $destination)  
{
    if (is_dir($source) == false)  
    {
        exit("The Source Directory Is Not Exist!");  
    }

    if (is_dir($source) !== false)  
    {  
        mkdir($destination, 0777);  
    }

    $handle = opendir($source);  

    while (false !== ($file = readdir($handle)))  
    {  
        if ($file != "." && $file != ".." && $file != ".svn")  
        {  
            is_dir("$source/$file")?  
            copy_dir("$source/$file", "$destination/$file"):  
            copy("$source/$file", "$destination/$file");  
        }  
    }  

    closedir($handle);  
}

//国际化语言设置
/*
$Translate = new Zend_Translate('gettext', APP_PATH . '/data/locales/', 'zh_CN', array(
    'scan' =>Zend_Translate::LOCALE_DIRECTORY
));

//$Translate->setLocale('auto');
$Translate->setLocale('zh_CN');
*/

//初始化语言包
if (function_exists('_'))
{
    //init_locale(APP_PATH . '/data/locales/', 'zh_CN', 'HelloWorld');
}
else
{
    function _($str)
    {
        return $str;
    }
}

//$Translate = new Lable();

/**
 * Determines if the current version of PHP is greater then the supplied value
 *
 * Since there are a few places where we conditionally test for PHP > 5
 * we'll set a static variable.
 *
 * @access  public
 * @param   string
 * @return  bool
 */
function is_php($version = '5.0.0')
{
    static $_is_php;
    $version = (string)$version;
    
    if (!isset($_is_php[$version]))
    {
        $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
    }

    return $_is_php[$version];
}

/**
 * 转义字符函数
 *
 * @param mixed $content  contents should be addslashes
 *
 * @return mixed  $content
 *
 */
function quotes(&$content)
{
    if(is_array($content))
    {
        foreach ($content as $key=>$value)
        {
            $content[$key] = quotes($value);
        }
    }
    else
    {
        $content = addslashes($content);
    }

    return $content;
}

function unquotes(&$content)
{
    if (is_array($content))
    {
        foreach($content as $key=>$value)
        {
            $content[$key] =unquotes($value);
        }
    }
    else
    {
        $content = stripslashes($content);
    }

    return $content;
}

//如果使用zend, 则关掉此处
function __autoload($class_name)
{
    if (!class_exists($class_name))
    {
        $class_path = str_replace('_', '/', $class_name);
        //$class_path = $class_path . '.php';

        $class_file_path = MOD_PATH . '/' . $class_path . '.php';

        if (file_exists($class_file_path))
        {
            import($class_file_path);
        }
        else
        {
            $class_file_path = LIB_PATH . '/' . $class_path . '.php';

            if (file_exists($class_file_path))
            {
                import($class_file_path);
            }
            else
            {
                $class_file_path = CTL_PATH . '/' . $class_path . '.php';

                if (file_exists($class_file_path))
                {
                    import($class_file_path);
                }
            }
        }

        if (!class_exists($class_name) && !interface_exists($class_name))
        {
            //throw new Exception('Class ' . $class_name . ' does not exists : ' . $class_path);
            error_header(404, 'Page Not Found');
            //echo 'Class ' . $class_name . ' does not exists : ' . $class_path;
            throw new Exception('Class ' . $class_name . ' does not exists : ' . $class_path);
        }
    }
}

function import($file_path=null, $flag=true)
{
    global $import_file_row;

    array_unshift($import_file_row, $file_path);

    if ($flag)
    {
        include_once $file_path;
    }
}

function check_request()
{
    if (SERVER_HOST == 'youleen.com')
    {
        if ($_SERVER['DOCUMENT_ROOT'])
        {
            if ($_SERVER['HTTP_REFERER'])
            {
                $referer_url_row = parse_url($_SERVER['HTTP_REFERER']);

                if ($referer_url_row['host'] != $_SERVER['SERVER_NAME'])
                {
                    die('禁止通过此途径访问!');
                }

                if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest')
                {
                    die('请使用浏览器正常途径访问!');
                }
            }
            else
            {
                die('禁止通过此途径访问');
            }
        }
    }
    else
    {
        
    }
}

if (!function_exists('clean_cache'))
{
    function clean_cache($dir=null, $del_dir=null) 
    {
        if (is_dir($dir))
        {
            $dh = opendir($dir);

            while(false !== ($f = readdir($dh)))
            {
                if($f == '.' || $f=='..')
                {
                    continue;
                }
                elseif(is_dir($dir . '/' . $f))
                {
                    clean_cache($dir . '/' . $f, $del_dir);
                }
                else
                {
                    unlink($dir . '/' . $f);            
                }
            }

            closedir($dh);

            if($del_dir && 'cache' != $dir)
            {
                rmdir($dir);
            }

            return true;
        }
        else
        {
            return false;
        }
    }
}


/*
mkdir('E:/to1/my1/file1', 0777, true);

if (!file_exists("E:/to/my/file"))
{
    make_dir_path("E:/to/my/file");
}
*/

function make_dir_path($path)
{
    if (!file_exists($path))
    {
        make_dir_path(dirname($path));
        mkdir($path, 0777);
    }
}

function l()
{
    if (!preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si', $_SERVER['HTTP_USER_AGENT'] , $m) || !version_compare($m[1][0], '0.0.6', '>='))
    {
        $Logger   = &Log::singleton('file', APP_PATH . '/data/logs/db.log', '', array(), PEAR_LOG_DEBUG);

        $content = func_get_args();
        $len = count($content) - 1;

        for ($i=$len; $i>=0; $i--)
        {
            $Logger->log($content[$i]);
        }
    }
    else
    {
        $FirePHP = new FirePHP();

        if ($FirePHP)
        {
            $instance = $FirePHP->getInstance(true);
            $args = func_get_args();
            return call_user_func_array(array($instance,'fb'),$args);
        }
    }
}

function fb()
{
    if ('cli' == SAPI)
    {
        //print_r(func_get_args());
        $content = func_get_args();
        $len = count($content) - 1;

        for ($i=$len; $i>=0; $i--)
        {
            print_r($content[$i]);
        }

        echo "\n";
    }
    else
    {
        if (!preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si', $_SERVER['HTTP_USER_AGENT'] , $m) || !version_compare($m[1][0], '0.0.6', '>='))
        {
            /*
            $conf = array('error_prepend' => '<font color="#ff0000"><pre>','error_append'  => '</pre></font>');

            $this->logger   = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
            $this->logger->log($sql);
            $this->logger->log($rs->getMessage());
            */

            /*
            $conf = array('error_prepend' => '<font color="#ff0000"><pre>','error_append'  => '</pre></font>');

            $this->logger   = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
            $this->logger->log($sth->query_string);
            $this->logger->log($sth->errorInfo());

            $this->logger   = &Log::singleton('firebug', '',  'PHP', $conf, PEAR_LOG_DEBUG);
            $this->logger->log($sql,     PEAR_LOG_DEBUG);

            //zend log
            $logger = new Zend_Log();
            $writer = new Zend_Log_Writer_Firebug();
            $logger->addWriter($writer);
            Zend_Registry::set('logger',$logger);

            $logger = Zend_Registry::get('logger');



            $request = new Zend_Controller_Request_Http();
            $response = new Zend_Controller_Response_Http();
            $channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
            $channel->setRequest($request);
            $channel->setResponse($response);

            $logger->log('This is a log message!', Zend_Log::INFO);
            $logger->log($table,  Zend_Log::INFO);

            $channel->flush();
            $response->sendHeaders();
            */

        }
        else
        {
            $FirePHP = new FirePHP();

            if ($FirePHP)
            {
                $instance = $FirePHP->getInstance(true);
                $args = func_get_args();
                return call_user_func_array(array($instance,'fb'),$args);
            }
        }
    }

    return true;
}

function get_ip() 
{
    if (getenv('HTTP_CLIENT_IP')) 
    {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    elseif(getenv('HTTP_X_FORWARDED_FOR')) 
    {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif(getenv('HTTP_X_FORWARDED')) 
    {
        $ip = getenv('HTTP_X_FORWARDED');
    }
    elseif(getenv('HTTP_FORWARDED_FOR')) 
    {
        $ip = getenv('HTTP_FORWARDED_FOR');
    }
    elseif(getenv('HTTP_FORWARDED')) 
    {
        $ip = getenv('HTTP_FORWARDED');
    }
    else
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}

function ceil_r($num)
{
    return ceil(round($num, 10));
}

function floor_r($num)
{
    return floor(round($num, 10));
}

function mres($str)
{
    return addslashes($str);
    //return mysql_real_escape_string($str);
}

/**
 * 取得当前时间
 *
 * @return  int $time 是否成功
 *
 */
function get_time()
{
    if ('cli' == SAPI)
    {
        $time = time();         
    }
    else
    {
        if (isset($_SERVER['REQUEST_TIME']))
        {
            $time = $_SERVER['REQUEST_TIME'];
        }
        else
        {
            $time = time();
        }
    }

    return $time;
}

/**
 * 取得执行结果
 *
 * @return  array   $rs_row             是否成功
 */
function is_ok(&$rs_row=array())
{
    $rs = true;

    if (in_array('0', $rs_row) || in_array(false, $rs_row) || in_array('', $rs_row))
    {
        $rs = false;
    }

    return $rs;
}

function get_query1() 
{
    $query_string = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']) +1, strlen($_SERVER['REQUEST_URI']));
    
    if ($length = strpos($query_string, '?')) 
    {
        $query_string = substr($query_string, 0, $length);
    }
    
    return $query_string;
}

/**
 * 获得友好的URL访问
 */
function get_query()
{
    $_SGETS   = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    $_SLEN    = count($_SGETS);
    $_SGET    = $_GET;

    for($i=0; $i<$_SLEN; $i+=2)
    {
        if(!empty($_SGETS[$i]) && !empty($_SGETS[$i+1])) $_SGET[$_SGETS[$i]]=$_SGETS[$i+1];
    }

    if (!isset($_REQUEST['ctl']))
    {
        $_SGET['ctl'] = !empty($_SGET['ctl']) && is_string($_SGET['ctl']) ? trim($_SGET['ctl']) : 'main';
    }

    if (!isset($_REQUEST['act']))
    {
        $_SGET['act'] = !empty($_SGET['act']) && is_string($_SGET['act']) ? trim($_SGET['act']) : 'index';
    }

    return $_SGET;
}

/**
 * 生成链接URL
 *
 */
function setUrl($arr)
{
    global $global;
    
    $query_string = '';

    if($global['urlmode'] == 2)
    {
        foreach($arr as $k=> $v)
        {
            $query_string .= $k. '/' . $v. '/';
        }
    }

    $query_string .= $global['urlsuffix'];

    return $query_string;
}

/**
 * 本地化  I18N 程序范例开始 
 *
 *
 * @param string $lan_path 设置某个域的mo文件路径  
 * @param string $lang     bsd use zh_CN.UTF-8
 * @param string $domain   定义要用的mo文件名称，常规来说，我们都把PACKAGE的名称定义和程序名称相同。 
 * @return void 
 */
function init_locale($lan_path, $lang, $domain)
{
    setlocale(LC_ALL, $lang);   //// bsd use zh_CN.UTF-8

    bindtextdomain($domain, $lan_path); //设置某个域的mo文件路径  
    bind_textdomain_codeset($domain, 'UTF-8'); //设置mo文件的编码为UTF-8    
    textdomain($domain); //设置gettext()函数从哪个域去找mo文件 
}


if (!function_exists('get_called_class')) 
{
    function get_called_class() 
    {
        $bt = debug_backtrace();
        $l = 0;
        do 
        {
            $l++;
            $lines = file($bt[$l]['file']);
            $callerLine = $lines[$bt[$l]['line'] - 1];
            preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
            
            if ($matches[1] == 'self') 
            {
                $line = $bt[$l]['line'] - 1;
                
                while ($line > 0 && strpos($lines[$line], 'class') === false) 
                {
                    $line--;
                }
                preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
            }
        }
        
        while ($matches[1] == 'parent' && $matches[1]);
        
        return $matches[1];
    }
}

/**
 * 通知客户端错误原因
 *
 * @param  int $error_no
 * @param  string $error_msg
 */
function error_header($error_no, $error_msg)
{
    header('HTTP/1.0 ' . $error_no . ' ' . $error_msg);
}
?>